#!/user/bin/env node

const log = console.log,
      http = require('http'),
      cp = require('child_process'),
      qs = require('querystring');
let result = '';


http.createServer((req,res)=>{
  if(req.url != '/'){
    err(res);
    log('404 not found page');
    return;
  }

  log(`${req.method} ${req.url} HTTP/${req.httpVersion}`);
  log('url:',req.url,req.method);
  log('header:',req.headers);
  
  switch(req.method){
    case 'GET':
      show(res);
      break;
    case 'POST':
      add(req,res);
      break;
    default:
      err(res);
      break;
  }
}).listen(3000);


function show(res){
  let html = `
    <!DOCTYPE html>
      <html>
        <head>
        <meta charset="UTF-8">
          <title>Linux Command</title>
          </head>
        <body>
          <h1>Input a Linux Command</h1>
          <form method="post" action="/">
          <p><input type="text" name="data" />
          <input type="submit" value="execute" /></p>
          </form>
          <div><pre style="font-family: Consolas;">${result}</pre></div>
        </body>
      </html>`;

    res.statusCode = 200;
    res.setHeader('Content-Type','text/html');
    res.setHeader('content-Length',Buffer.byteLength(html));
    res.end(html);
}

function add(req,res){
  let data = '';
  req.on('data',(chunk)=>{
    data += chunk;
  });
  req.on('end',()=>{
    data = qs.parse(data).data;
    
    if(data === ''){
      result = 'pleace input!';
      show(res);
    }else{
      log(data);
      cp.exec(data,(err,stdout,stderr)=>{
        result = (err === null)?stdout:stderr;
        show(res);
      });
    }
  });
}

function err(res){
  let msg = 'not found!';
  res.statusCode = 404;
  res.setHeader('Content-Length',msg.length);
  res.setHeader('Content-Type','text/plain');
  res.end(msg);
}
